//
//  PersonalEditInformationTableViewController.m
//  suRead
//
//  Created by 龚浩植 on 16/4/25.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "PersonalEditInformationTableViewController.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "CDImagePicker.h"
#import "AccountManager.h"
#import "ServiceUserNew.h"
#import "UIImageView+WebCache.h"
#import "RKAlertView.h"
#import "Masonry.h"
#import "SDWebImageManager.h"

#import "MyWelfareViewController.h"

#import "AppDelegate.h"
#import "UIApplication+VisibleViewController.h"
#import "ModalViewController.h"

@interface PersonalEditInformationTableViewController ()<UIActionSheetDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIButton *buttonPhoneEdit;
//@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UIImageView *userIconImage;
@property (weak, nonatomic) IBOutlet UIView *iconBoardView;
@property (weak, nonatomic) IBOutlet UIImageView *thirdPartIcon;
@property (weak, nonatomic) IBOutlet UILabel *thirdPartNameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *editImage;
@property (strong, nonatomic)CDImagePicker *imagePicker;

@property (weak, nonatomic) IBOutlet UIButton *backMenu;

@property (weak, nonatomic) IBOutlet UIButton *dynButton;

@property (strong, nonatomic)NSString *code;

@property (strong,nonatomic) NSString *fuli;
@end



@implementation PersonalEditInformationTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self) weka_self = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(-34.0f, 0.0f, 0.0f, 0.0);
    self.tableView.allowsSelection = NO;
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 0;
    [self setFuli:@"0"];

    if ([AccountManager sharedAccountManager].f_phone_num.length) {
        self.buttonPhoneEdit.hidden = YES;
        [self.dynButton setTitle: @"去看看我的福利" forState: UIControlStateNormal];
        [self setFuli:@"1"];
    }
    AccountManager *account = [AccountManager sharedAccountManager];
    self.userNameTextField.text = account.f_nickname;
    self.phoneTextField.text = account.f_phone_num;
    if (account.f_isQQBinding) {
        self.thirdPartIcon.image = [UIImage imageNamed:@"UMS_qq_on"];
        self.thirdPartNameLabel.text = @"QQ绑定";
    }
    else if (account.f_isSinaBinding) {
        self.thirdPartIcon.image = [UIImage imageNamed:@"UMS_sina_on"];
        self.thirdPartNameLabel.text = @"微博绑定";
    }
    else if (account.f_isWechatBinding) {
        self.thirdPartIcon.image = [UIImage imageNamed:@"UMS_wechat_on"];
        self.thirdPartNameLabel.text = @"微信绑定";
    }
    self.iconBoardView.layer.cornerRadius = 77/2.0f;
    self.iconBoardView.layer.masksToBounds = YES;
    self.userIconImage.layer.cornerRadius = 36.0f;
    self.userIconImage.layer.masksToBounds = YES;
    [self.userIconImage sd_setImageWithURL:[NSURL URLWithString:account.f_user_img] placeholderImage:[UIImage imageNamed:@"icon_personal"]];

    self.editImage.userInteractionEnabled = YES;
    NSLog(@"%@",account.f_user_img);
    UITapGestureRecognizer *iconTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(iconTap:)];
    [self.editImage addGestureRecognizer:iconTapGes];
//    self.userIconImage.image = [UIImage imageNamed:[AccountManager sharedAccountManager].f_user_img];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self.phoneTextField setDelegate:self];
    self.phoneTextField.userInteractionEnabled= YES;
    [self.userNameTextField setDelegate:self];
    self.userNameTextField.userInteractionEnabled= YES;
    
    self.phoneTextField.tag=101;
    self.userNameTextField.tag=102;

}



- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if(textField.tag==101) {
       // if ([AccountManager sharedAccountManager].f_phone_num.length) {
            [self showAndEditPHONE];
        //}
    }else if(textField.tag ==102) {
        if ([AccountManager sharedAccountManager].f_nickname.length) {
            [self showAndEditAlias];
        }
    }
//
    return false;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([AccountManager sharedAccountManager].f_isWechatBinding ==YES||[AccountManager sharedAccountManager].f_isSinaBinding==YES||[AccountManager sharedAccountManager].f_isQQBinding==YES) {
        return 2;

    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)iconTap:(UITapGestureRecognizer *)ges
{
    [self.view endEditing:YES];
    UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相",@"相册", nil];
    [chooseImageSheet showInView:self.view];

}

#pragma mark 拍照上传
- (void)uploadByCamera:(UIImagePickerControllerSourceType)type
{
    __weak typeof(self) weakSelf = self;
    self.imagePicker = [CDImagePicker imagePickerWith:self type:type completeBlock:^(NSString *imagePath_) {
        [[SDWebImageManager sharedManager].imageCache clearWithCacheType:SDImageCacheTypeDisk completion:nil];
        [[SDWebImageManager sharedManager].imageCache clearWithCacheType:SDImageCacheTypeMemory completion:nil];
        self.userIconImage.image = [UIImage imageWithContentsOfFile:imagePath_];
        
        [weakSelf showHUDProgress:@""];
        [ServiceUserNew doUpload:imagePath_ success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
            
            if ([responseObject objectForKey:@"cover_path"]) {
                
                // 拼地址
                NSString *imageUrl = [base_url stringByAppendingString:[responseObject objectForKey:@"cover_path"]];
                [ServiceUserNew doModifyUserInfo:@"" cover:imageUrl sex:1 success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                    [weakSelf removeHUDProgress];
                    [weakSelf showHUDText:message];
                    
                    [AccountManager sharedAccountManager].f_user_img = imageUrl;
                } failure:^(NSString * _Nonnull message) {
                    [weakSelf removeHUDProgress];
                    [weakSelf showHUDText:message];
                }];
            } else {
                [weakSelf removeHUDProgress];
                [weakSelf showHUDText:@"上传失败"];
            }
            
        } failure:^(NSString * _Nonnull message) {
            [weakSelf removeHUDProgress];
            [weakSelf showHUDText:message];
        }];
        
    }];
    [self.imagePicker choose];
}
#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0://Take picture
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                [self uploadByCamera:UIImagePickerControllerSourceTypeCamera];
            }
            else
            {
                NSLog(@"模拟器无法打开相机");
            }
            break;
        case 1:
        {
            [self uploadByCamera:UIImagePickerControllerSourceTypePhotoLibrary];
        }
            break;
        default:
            break;
    }
}

- (IBAction)backMenu:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)editMyAlias:(id)sender {
    [self showAndEditAlias];
}

- (IBAction)dynButtonTouch:(id)sender {
    if([[self fuli] isEqualToString:@"1"]) {
        UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
        MyWelfareViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"MyWelfareViewController"];
        controller.hidesBottomBarWhenPushed = YES;
        [[[UIApplication sharedApplication] visibleViewController].navigationController pushViewController:controller animated:YES];
    }else {
        [self showAndEditPHONE];
    }
}

- (IBAction)editMyPhone:(id)sender {
   [self showAndEditPHONE];
}


-(void)showAndEditPHONE {
    if ([AccountManager sharedAccountManager].f_phone_num.length) {
        return;
    }
    
    //显示模态窗体
    ModalViewController *mvc =  [[ModalViewController alloc] init];
    mvc.delegate = self;
    [mvc initStyle];
    
    [self presentViewController:mvc animated:YES completion:^(void){
        mvc.view.superview.backgroundColor = [UIColor clearColor];
        
    }];
    
}

-(void)modalViewControllerDidClickedDismissButton:(ModalViewController *)viewController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)showAndEditAlias {
    
    [RKAlertView showAlertPlainTextWithTitle:@"修改昵称" message:[NSString stringWithFormat:@"请输入新昵称"] cancelTitle:@"取消" confirmTitle:@"确认" alertViewStyle:UIAlertViewStylePlainTextInput confrimBlock:^(UIAlertView *alertView) {
        
        NSString *name = [alertView textFieldAtIndex:0].text;
        
        if (!name.length) {
            [self showHUDText:@"新昵称不能为空！"];
            return;
        }
        if ([name isEqualToString:[NSString stringWithFormat:@"%@",[AccountManager sharedAccountManager].f_nickname]]) {
            [self showHUDText:@"新昵称不能与原昵称相同！"];
            return;
        }
        
        // 修改昵称
        [ServiceUserNew doModifyUserInfo:name cover:@"" sex:1 success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
            [self showHUDText:message];
            [AccountManager sharedAccountManager].f_nickname = name;
            [self.tableView reloadData];
            self.userNameTextField.text = [AccountManager sharedAccountManager].f_nickname;
        } failure:^(NSString * _Nonnull message) {
            [self showHUDText:message];
        }];
        
        NSLog(@"确认了输入：%@",[alertView textFieldAtIndex:0].text);
    } cancelBlock:^{
        NSLog(@"取消了");
    }];

    
}

- (IBAction)editSubmit:(id)sender {
    UIButton *but = sender;
    if (but.tag == 0) {
        [self showAndEditAlias];
    }
    else if(but.tag == 1)
    {
        [self showAndEditPHONE];
    }
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}


-(void)back {
    NSLog(@"come in");
}

@end
